package gqz.mvvm.adapter;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Created by Administrator on 2017/12/2.
 */

public class MyBaseAdapter<T> extends BaseAdapter {

    private LayoutInflater inflater;
    private Context context;
    private int layoutId;
    private List<T> list;
    private int variableId;
    private MyItemClickListener clickListener;

    public MyBaseAdapter(Context context, int layoutId, List<T> list, int resId, MyItemClickListener clickListener) {
        this.context = context;
        this.layoutId = layoutId;
        this.list = list;
        this.variableId = resId;
        this.clickListener = clickListener;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewDataBinding dataBinding;
        if (convertView == null) {
            dataBinding = DataBindingUtil.inflate(inflater, layoutId, parent, false);
        } else {
            dataBinding = DataBindingUtil.getBinding(convertView);
        }
        dataBinding.setVariable(variableId, list.get(position));
        View rootView = dataBinding.getRoot();
        rootView.setTag(position);
        return rootView;
    }

    public void onItemClick(View view) {
        clickListener.onItemClick(view);
    }

    public interface MyItemClickListener {
        void onItemClick(View view);
    }
}

